import json
import pymysql
import requests
from playwright.async_api import async_playwright
import redis
import asyncio

redis_con = redis.Redis(host='127.0.0.1', password="xhhg123456", db=2, decode_responses=True)

bigdata_con = pymysql.connect(
    host="121.4.69.146", user='root', password='xhhg@2020', port=3306, db="big_data", use_unicode=True, charset='utf8')
bigdata_cur = bigdata_con.cursor()


def get_login():
    """获取登录token"""
    headers = {"Accept": "application/json"}
    url = 'https://api.xinhehonggu.com/api/auth/login'
    phone = '18866668888'
    password = 'xhhg2019'
    source = 'admin'
    data = {
        'method': '1',
        'phone': phone,
        'password': password,
        'source': source,
    }
    r = requests.post(url=url, data=data, headers=headers, verify=False)
    res_dict = r.json()
    token = res_dict['data']['token']
    return token


async def chaxun_sqh(url, token, headers, sem):
    async with sem:
        async with async_playwright() as p:
            storage_state_path = f'./auth/WB_state.json'
            with open(storage_state_path) as file:
                storage_state = json.load(file)
                origins = storage_state.get('origins')
                local_stroge_list = [item.get('localStorage')
                                     for item in origins]
                for local_stroge in local_stroge_list:
                    for item in local_stroge:
                        if item.get('name') == 'ACCESS_TOKEN':
                            authorization = item.get('value')
            print(f'成功读取WB登录信息:{authorization}')
            browser = await p.firefox.launch()
            context = await browser.new_context(
                base_url='https://cpquery.cponline.cnipa.gov.cn', storage_state=storage_state_path, ignore_https_errors=True)
            context.set_default_timeout(300000)
            context.set_default_navigation_timeout(300000)
            page = await context.new_page()
            page.set_default_timeout(300000)
            page.set_default_navigation_timeout(300000)
            await page.goto(
                'https://cpquery.cponline.cnipa.gov.cn/chinesepatent/index')
            # await page.wait_for_load_state('networkidle')
            while redis_con.scard('外部订单申请号'):
                sqh = redis_con.spop('外部订单申请号')
                sqh = sqh.replace('ZL', '')
                print(f'开始查询:{sqh}')
                api_request_context = context.request
                post_headers = {
                    "Accept": "application/json, text/plain, */*",
                    "Content-Type": "application/json;charset=utf-8",
                    "Authorization": 'Bearer ' + authorization,
                    "userType": "USER_RZ_DAILIJIG"
                }
                sqxx_response = await api_request_context.post(
                    '/api/view/gn/sqxx', data={'zhuanlisqh': sqh}, headers=post_headers, timeout=120000)
                try:
                    patent_status_res_json = await sqxx_response.json()
                    patent_status_data = patent_status_res_json.get('data')
                    state = patent_status_data.get(
                        'zhuluxmxx').get('zhuluxmxx').get('anjianywzt')
                    if (state == '--') or (state is None):
                        state = ''
                except:
                    state = ''
                res_sqh = "CN" + sqh[0:12] + "." + sqh[-1]
                print(f'{res_sqh}:{state}')
                data = {
                    'token': token,
                    'secret': 'th45gdk1df5rdb51',
                    "patentNo": res_sqh,  # 申请号
                    'lawStatus': state  # 案件状态
                }
                res = requests.put(url=url, headers=headers, data=data)
                jsondata = json.loads(res.text)
                print(jsondata, sqh, state)
                print('----' * 10)
                await page.reload()
            # page.wait_for_load_state('networkidle')


async def main(url, token, headers):
    max_process = 5
    sem = asyncio.Semaphore(max_process)  # 最大并发量
    task_list = [asyncio.create_task(chaxun_sqh(
        url, token, headers, sem))for _ in range(max_process)]
    await asyncio.gather(*task_list)


def insert_data_redis():
    # 读取数据插入redis
    select_sql = "SELECT distinct application_number FROM `external_orders`"
    con_mysql = pymysql.connect(host="112.125.25.114", port=3306, user='python',
                                password='pythonselect', db="mykhadmin", use_unicode=True, charset='utf8')
    cur_m = con_mysql.cursor()
    cur_m.execute(select_sql)
    data_list = cur_m.fetchall()
    cur_m.close()
    con_mysql.close()
    print(f'共计:{len(data_list)}')
    for data in data_list:
        sqh = data[0].replace('ZL', '')
        redis_con.sadd('外部订单申请号', sqh)
    print('全部申请号加入redis')


if __name__ == '__main__':
    # step1: redis加入数据
    # insert_data_redis()
    # step2：更新外部订单接口
    token = get_login()
    print(f'读取token:{token}')
    headers = {"Accept": "application/json"}
    # url = "http://test.api.whxhhgip.com/api/external_order/update"  # 测试接口
    url = "https://api.xinhehonggu.com/api/external_order/update"  # 系统外部订单更新接口
    # 获取案件专利信息，本地有数据有查询本地数据库，没有就网上爬  申请号在开发库的表external_orders
    asyncio.run(main(url, token, headers))
    bigdata_cur.close()
    bigdata_con.close()
